package com.jd.myaaaccount;

import com.jd.myaaaccount.entity.Family;
import com.jd.myaaaccount.model.Common;
import com.jd.myaaaccount.model.FamilyModel;
import com.jd.myaaaccount.util.AlertDialogHelper;
import com.jd.myaaaccount.util.ErrorCode;
import com.jd.myaaaccount.util.JsonHelper;
import com.jd.myaaaccount.util.OperateCode;
import com.jd.myaaaccount.util.MD5Helper;
import com.jd.myaaaccount.util.QRCodeHelper; 
 
import android.os.Bundle;
import android.os.Handler; 
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap; 
import android.text.InputType;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener; 
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class EditFamilyActivity extends BaseActivity {

	private TextView tvTitle;
	private TextView tvID;
	private EditText etID; 
	private EditText etName;
	private EditText etPassword;
	private Button btnCreate;
	private ImageView ivScanCode;
	private ImageView ivQRCode;

	private Handler handler;
	private int operateFlag = 1;// 操作标记 1 创建家庭 2查看3 加入家庭

	private FamilyModel familyModel;

	private Family family;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_edit_family);
		familyModel = new FamilyModel(this);
		Intent intent = getIntent();
		operateFlag = intent.getIntExtra("operateFlag", OperateCode.ADD);

		iniControl();

		if (operateFlag == OperateCode.SCAN) {
			family = new Family();
			family.setNumber(intent.getIntExtra("number", 0));
			family.setName(intent.getStringExtra("name"));
			family.setPassword(intent.getStringExtra("password"));

			tvTitle.setText("家庭:" + intent.getStringExtra("name"));
			showFamily();
			// 生成二维码
			String json = JsonHelper.getString(family);
			Bitmap bmp = QRCodeHelper.getQRCode(json, 200, 200);
			ivQRCode.setImageBitmap(bmp);
		}

		handler = new Handler() {
			@Override
			public void handleMessage(android.os.Message msg) {
				pd.cancel();
				switch (msg.what) {
				case OperateCode.ADD:// 创建结果
					if (msg.arg1 == ErrorCode.SUCCESS) {// 创建成功
						new AlertDialog.Builder(EditFamilyActivity.this)
								.setTitle("提示")
								.setMessage("创建成功")
								.setPositiveButton("确定",
										new DialogInterface.OnClickListener() {
											@Override
											public void onClick(
													DialogInterface arg0,
													int arg1) {
												setResult(ErrorCode.SUCCESS);
												finish();
											};
										}).show();
					} else if (msg.arg1 == ErrorCode.TOKEN_OVERDUE) {
						Common.loginTimeOut(EditFamilyActivity.this);
					} else {// 创建失败
						Common.showErrorInfo(EditFamilyActivity.this,
								msg.arg1, "创建失败", 0);
					}
					break;
				case OperateCode.JOIN:// 加入结果
					if (msg.arg1 == ErrorCode.SUCCESS) {// 加入成功
						new AlertDialog.Builder(EditFamilyActivity.this)
								.setTitle("提示")
								.setMessage("加入成功")
								.setPositiveButton("确定",
										new DialogInterface.OnClickListener() {
											@Override
											public void onClick(
													DialogInterface arg0,
													int arg1) {
												setResult(ErrorCode.SUCCESS);
												finish();
											};
										}).show();
					} else if (msg.arg1 == ErrorCode.TOKEN_OVERDUE) {
						Common.loginTimeOut(EditFamilyActivity.this);
					} else if (msg.arg1 == ErrorCode.FAMILY_OR_PWD_WRONG) {
						Toast.makeText(EditFamilyActivity.this, "家庭不存在或密码错误",
								Toast.LENGTH_SHORT).show();
					} else {// 加入失败
						Toast.makeText(EditFamilyActivity.this, "加入失败",
								Toast.LENGTH_SHORT).show();
					}
					break;

				case 123:
					ivQRCode.setImageBitmap((Bitmap) msg.obj);
					break;
				default:
					break;
				}
			};
		};

		// 操作
		btnCreate.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				if (operateFlag == OperateCode.ADD) {
					createFamily();
				} else if (operateFlag == OperateCode.SCAN) {

				} else if (operateFlag == OperateCode.JOIN) {
					joinFamily();
				}
			}
		});

		// 扫码加入
		ivScanCode.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(EditFamilyActivity.this,
						ScanCodeActivity.class);
				startActivityForResult(intent, OperateCode.SCAN_COD);
			}
		});
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.create_home, menu);
		return true;
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == OperateCode.SCAN_COD) {
			String json = data.getStringExtra("code");
			Log.e("json", json);
			if (json.equals(""))
				return;
			family = JsonHelper.getObject(json, Family.class);
			showFamily();
		}
	}

	private void iniControl() {
		tvTitle = (TextView) findViewById(R.id.tvTitle);
		tvID = (TextView) findViewById(R.id.tvID);
		etID = (EditText) findViewById(R.id.etID);
		//tvName = (TextView) findViewById(R.id.tvName);
		etName = (EditText) findViewById(R.id.etName);
		etPassword = (EditText) findViewById(R.id.etPassword);
		btnCreate = (Button) findViewById(R.id.btnCreate);
		ivScanCode = (ImageView) findViewById(R.id.ivScanCode);
		ivQRCode = (ImageView) findViewById(R.id.ivQRCode);

		if (operateFlag == OperateCode.ADD) {// 创建家庭
			tvID.setVisibility(View.GONE);
			etID.setVisibility(View.GONE);
			ivScanCode.setVisibility(View.GONE);
		} else if (operateFlag == OperateCode.JOIN) {// 加入家庭
			tvTitle.setText("加入家庭");
			etName.setInputType(InputType.TYPE_CLASS_NUMBER);
			btnCreate.setText("加入");
			etName.setEnabled(false);
		} else if (operateFlag == OperateCode.SCAN) {
			// tvTitle.setText("家庭:"+);
			ivScanCode.setVisibility(View.GONE);
			etID.setEnabled(false);
			etName.setEnabled(false);
			etPassword.setEnabled(false);
			btnCreate.setVisibility(View.GONE);
		}
	}

	private void showFamily() {
		if (family == null)
			return;
		etID.setText(String.valueOf(family.getNumber()));
		etName.setText(family.getName());
		etPassword.setText(family.getPassword());
	}

	/**
	 * 创建家庭
	 */
	private void createFamily() {
		String name = etName.getText().toString();
		if (name.equals("")) {
			Toast.makeText(EditFamilyActivity.this, "名称不能为空",
					Toast.LENGTH_SHORT).show();
			return;
		}
		String password = etPassword.getText().toString();
		if (password.equals("")) {
			Toast.makeText(EditFamilyActivity.this, "密码不能为空",
					Toast.LENGTH_SHORT).show();
			return;
		}
		password = MD5Helper.md5(password);
		final Family family = new Family();
		family.setName(name);
		family.setPassword(password);

		pd = AlertDialogHelper.showWaitProgressDialog(
				EditFamilyActivity.this, "正在创建…");
		new Thread(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				familyModel.create(family, handler);
			}
		}).start();
	}

	/**
	 * 加入家庭
	 */
	private void joinFamily() {
		int nb;
		String pwd;
		if (family != null) {
			nb = family.getNumber();
			pwd = family.getPassword();

		} else {
			if (etName.getText().toString().equals("")) {
				Toast.makeText(EditFamilyActivity.this, "ID不能为空",
						Toast.LENGTH_SHORT).show();
				return;
			}
			try {
				nb = Integer.parseInt(etName.getText().toString());
			} catch (Exception e) {
				Toast.makeText(EditFamilyActivity.this, "ID格式错误",
						Toast.LENGTH_SHORT).show();
				return;
			}

			if (etPassword.getText().toString().equals("")) {
				Toast.makeText(EditFamilyActivity.this, "密码不能为空",
						Toast.LENGTH_SHORT).show();
				return;
			}
			pwd = MD5Helper.md5(etPassword.getText().toString());
		}
		final String password = pwd;
		final int number = nb;

		pd = AlertDialogHelper.showWaitProgressDialog(
				EditFamilyActivity.this, "处理中…");
		new Thread(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				familyModel.join(number, password, handler);
			}
		}).start();
	}
}
